#!/usr/bin/env python2.5
#
#

__copyright__ = 'this file is in the public domain'

from gozerbot.utils.log import enable_logging, rlog

rlog(10, 'GOZERAPP', 'STARTING VERSION 0.1 ALPHA')

from gozerbot.google.bot import GoogleBot
from gozerbot.eventbase import EventBase
from gozerbot.config import config
from gozerbot.periodical import periodical
from gozerbot.commands import cmnds
from gozerbot.plugins import plugins
from gozerbot.users import users

import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import sys, time, types

def checkuser(response):
    user = gusers.get_current_user()
    if not user:
        plzlogin = ("<a href=\"%s\">Sign in or register</a>." %
        gusers.create_login_url("/"))
        response.out.write(plzlogin)
        return (None, None, None)
    userhost = user.email() 
    nick = user.nickname()
    if not users.exist(userhost):
        try:
             users.add(nick, [userhost, ], ['USER', ])
        except Exception, ex:
             rlog(10, userhost, str(ex))
             self.response.out.write('failed to add %s as a user' % userhost)
             return (None, None, None)
    u = users.getuser(userhost)
    return (userhost, user, u)

def commandbox(response):
    response.out.write("""
          <form action="/dispatch/" method="post">
            <div><b>enter command:</b> <input type="commit" name="content"></div>
          </form>
          """)

def showcommands(response, perms=['USER', ]):
    cmndslist = cmnds.list(perms)
    cmndslist.sort()
    response.out.write('the bot allows the following commands:<br><br><i>%s</i>' \
% ' .. '.join(cmndslist))
    response.out.write('<br><br>')

def closer(response):
    response.out.write("</body></html>")

def webheader(response):
    """ create web header """
    response.headers['Content-Type'] = 'text/html'
    response.out.write('')
    response.out.write('')
    response.out.write('<html><H1>GOZERAPP 0.1 ALPHA</H1>')
    response.out.write('<i><b>gozerbot on the GAE</b></i><br><br>')
    response.out.write('the following plugins are loaded: %s' % ' .. '.join(plugins.list()))
    response.out.write('<br><br>see the help command .. it uses the plugin name as an argument<br><br>')

#focustxt = """<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
#   "http://www.w3.org/TR/html4/loose.dtd">
#<html>
focustxt = """
<head>
<script type="text/javascript">

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- John Munn  (jrmunn@home.com) -->

<!-- Begin
 function putFocus(formInst, elementInst) {
  if (document.forms.length > 0) {
   document.forms[formInst].elements[elementInst].focus();
  }
 }
// The second number in the "onLoad" command in the body
// tag determines the form's focus. Counting starts with '0'
//  End -->
</script>

</head>
<body onLoad="putFocus(0,0);">
"""

llevel = 2
config['loglevel'] = llevel
enable_logging(llevel)


import gozerbot.utils.log
gozerbot.utils.log.loglevel = llevel

rlog(10, 'gozerapp', 'loglevel is %s' % gozerbot.utils.log.loglevel)


# basic bot imports

# start periodical loop
#periodical.start()

# register plugins
plugins.regplugins()
    
        
# google app stuff

bot = GoogleBot('gozerapp')
users.make_owner(['bthate@gmail.com', ])

from google.appengine.api import users as gusers

class MainHandler(webapp.RequestHandler):

    def get(self):
        (userhost, user, u) = checkuser(self.response)
        if not user:
             return 
        self.response.out.write(focustxt)
        webheader(self.response)
        #showcommands(self.response, u.perms)
        commandbox(self.response)
        closer(self.response)

class DispatchHandler(webapp.RequestHandler):

    def get(self):
        (userhost, user, u) = checkuser(self.response)
        if not user:
            return
        self.response.out.write(focustxt)
        webheader(self.response)
        #showcommands(self.response, u.perms)
        commandbox(self.response)
        closer(self.response)

    def post(self):
        (userhost, user, u) = checkuser(self.response)
        if not user:
            return
        input = self.request.get('content')
        if not input:
            return
        self.response.out.write(focustxt)
        webheader(self.response)
        #showcommands(self.response, u.perms or 'USER')
        commandbox(self.response)
        self.response.out.write('<br>')
        nick = user.nickname()
        event = EventBase()
        event.origtxt = input.strip()
        event.txt = '!' + event.origtxt
        event.userhost = userhost
        event.nick = nick
        event.groupchat = False
        event.msg = True
        event.response = self.response
        event.request = self.request
        event.bot = bot
        event.bot.domsg(event, wait=True)
        self.response.out.write('</pre>')
        closer(self.response)

application = webapp.WSGIApplication([('/', MainHandler), \
                                          ('/dispatch/', DispatchHandler)],
                                       debug=False)

def main():
    global bot
    global plugins
    global application
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
